<?php
class Account extends Controller {
	 public function __construct() {
			 parent::Controller();
			 $this->load->helper("form");
			 $this->load->helper("url");
			 $this->load->library("errors");
			 $this->load->scaffolding("users");
			 $this->load->model("LocationsModel");
			 $this->load->model("AccountModel");
		 }
		 /** Private Functions  */
	 private function setLogin($username,$fname) {
			 $this->phpsession->save("username",$username);
			 $this->phpsession->save("logged_in",true);
			 $this->phpsession->save("fname",$fname);
		 }
	 private function sendForgotEmail($mailObj) {
			 $this->load->library('email');
			 $this->config->load('email');
			 $this->email->from('your@your-site.com', 'Your Name');
			 $this->email->to('mike@ensor.cc');
			 $this->email->subject('Email Test');
			 $this->email->message('Testing the email class.');
			 return $this->email->send();
		 }
		 /************** Views ***********/
	 public function forgot() {
			 $headerData = array(
				 "pageTitle"=>"Forgot Login | My Account | Washington Homebrewers Association",
				 "pageStyleIndex"=>0, /* Header/Background/Logo pairing */
				 "styleIncludes"=>array("<link rel=\"stylesheet\" type=\"text/css\" href=\"/styles/form.css\" />"),
				 "selectedNav"=>"" /* Selected top level nav */
				 );
			 $pageData = array();
			 $footerData = array();
			 $this->load->view("PageTemplate_header.php",$headerData);
			 $this->load->view("account/forgot.php",$pageData);
			 $this->load->view("PageTemplate_footer.php",$footerData);
		 }
	 public function index() {
			 if($this->phpsession->get("logged_in")) {
					 redirect("account/update");
				 } else {
					 $headerData = array(
						 "pageTitle"=>"My Account | Washington Homebrewers Association",
						 "pageStyleIndex"=>0, /* Header/Background/Logo pairing */
						 "styleIncludes"=>array("<link rel=\"stylesheet\" type=\"text/css\" href=\"/styles/form.css\" />"),
						 "selectedNav"=>"", /* Selected top level nav */
						 "sNavCallout"=>"Please fill in your Username and Password"
						 );
					 $pageData = array();
					 $footerData = array();
					 $this->load->view("PageTemplate_header.php",$headerData);
					 $this->load->view("account/index.php",$pageData);
					 $this->load->view("PageTemplate_footer.php",$footerData);
				 }
		 }
	 public function login() {
		 // process login, redirect to welcome page
			 $this->load->model('UserModel'); // Login model as loginObj
			 $loginResult = $this->UserModel->isValidLogin($_POST["username"],$_POST["passwd"]);
			 switch($loginResult) {
				 case $this->UserModel->LOGIN_INVALID_LOGIN_COMBO:
				 $this->phpsession->flashsave('error',Errors::getError(0));
				 redirect("account");
				 break;
				 case $this->UserModel->LOGIN_INVALID_LOGINNAME:
				 $this->phpsession->flashsave('error',Errors::getError(1));
				 redirect("account");
				 break;
				 case $this->UserModel->LOGIN_SUCCESS:
				 $rs = $this->db->query("SELECT profile.fname FROM profile,users WHERE profile.p_id=users.p_id AND users.username=?",array($_POST["username"]));
				 $fname = ($rs->num_rows()>0)?$rs->row()->fname:"";
				 $this->setLogin($_POST["username"],$fname);
				 redirect("welcome");
				 break;
				 }
		 }
	 public function logout() {
		 // logout, redirect to welcome page
			 $newdata = array(
				 'username'  => "",
				 'logged_in' => false
				 );
			 $this->phpsession->clear("username");
			 $this->phpsession->clear("logged_in");
			 redirect("welcome");
		 }
	 public function create() {
		 // display create, redirect to index
			 $headerData = array(
				 "pageTitle"=>"Create Login | My Account | Washington Homebrewers Association",
				 "pageStyleIndex"=>0, /* Header/Background/Logo pairing */
				 "styleIncludes"=>array("<link rel=\"stylesheet\" type=\"text/css\" href=\"/styles/form.css\" />"),
				 "selectedNav"=>"" /* Selected top level nav */
				 );
			 $pageData = array("best_time"=>$this->db->get("best_times"),
				 "best_days"=>$this->db->get("best_days"),
				 "state"=>$this->db->get("state"),
				 "location_type"=>$this->db->get("location_type"),
				 "form_button"=>"Create",
				 "form_action"=>"account/handleCreate");
			 $footerData = array();
			 $this->load->view("PageTemplate_header.php",$headerData);
			 $this->load->view("account/create.php",$pageData);
			 $this->load->view("PageTemplate_footer.php",$footerData);
		 }
	 public function update(){
			 if(!$this->phpsession->get("logged_in")) {
					 redirect("/account/");
					 return;
				 }
			 $fieldDefaultData = array();
			 $row = $this->db->query(
				 "SELECT 
				 users.username,
				 profile.fname,
				 profile.lname,
				 contact.phone,
				 contact.email,
				 contact.cell,
				 contact.fax,
				 profile.aha_number,
				 contact.best_time,
				 contact.best_days
				 FROM users,profile,contact
				 WHERE 
				 users.p_id=profile.p_id 
				 AND profile.contact_id=contact.contact_id 
				 AND users.username=? limit 1"
				 ,array($this->phpsession->get("username")));
			 $rs = $row->row_array();
			 $username = $this->phpsession->get("username");
			 $fieldDefaultData = array_merge($rs,$fieldDefaultData);
				 // get Location data
			 $locUserData = $this->LocationsModel->getLocationByUserId($this->AccountModel->getUserId($username));
			 $fieldDefaultData = array_merge($locUserData,$fieldDefaultData);
		 
			 $pageData = array("best_time"=>$this->db->get("best_times"),
				 "best_days"=>$this->db->get("best_days"),
				 "state"=>$this->db->get("state"),
				 "location_type"=>$this->db->get("location_type"),
				 "form_button"=>"Update",
				 "form_action"=>"account/handleUpdate",
				 "isUpdate"=>true,
				 "default_values"=>$fieldDefaultData
				 );
			 $headerData = array(
				 "pageTitle"=>"My Account | Washington Homebrewers Association",
				 "pageStyleIndex"=>1, /* Header/Background/Logo pairing */
				 "styleIncludes"=>array("<link rel=\"stylesheet\" type=\"text/css\" href=\"/styles/form.css\" />"),
				 "selectedNav"=>"" /* Selected top level nav */
				 );
			 $footerData = array();
			 $this->load->view("PageTemplate_header.php",$headerData);
			 $this->load->view("account/create.php",$pageData);
			 $this->load->view("PageTemplate_footer.php");
		 }
		 /*********** Handle Functions **********************/
	 public function handleForgot() {
			 echo $this->sendForgotEmail();
		 }
	 public function handleCreate($isUpdate=false){
			 $this->load->library('validation');
				 // users
			 if(!$isUpdate) {
					 $rules['username'] = "trim|required|xss_clean";
				 }
			 if(!$isUpdate || ($isUpdate && !empty($_POST["passwd"]))) {
					 $rules['passwd'] = "trim|required|matches[passwd2]";
					 $rules['passwd2'] = "trim|required|matches[passwd]";
				 }
				 // profile
			 $rules['fname'] = "trim|required";
			 $rules['lname'] = "trim|required";
				 // contact
			 $rules['phone'] = "trim|required";
			 $rules['email'] = "trim|required|valid_email";
				 // locations
			 $rules["name"] = "trim|required";
			 $rules["zipcode"] = "trim|required";
			 $rules["location_type"] = "trim|required";
		 
			 $this->validation->set_rules($rules);
			 if (!$this->validation->run()) {
					 $fields['username']	= 'Username';
					 $fields['passwd']	= 'Password';
					 $fields['passwd2']	= 'Password Confirmation';
					 $fields['email']	= 'Email Address';
					 $fields['fname']	= 'First Name';
					 $fields['lname']	= 'Last Name';
					 $fields['phone']	= 'Phone Number';
					 $fields['name']		= 'Location Name';
					 $fields['zipcode']		= 'Postal Code';
					 $fields['location_type'] = 'Location Type';
					 $this->validation->set_fields($fields);
				 
					 $pageData["best_time"]=$this->db->get("best_times");
					 $pageData["best_days"]=$this->db->get("best_days");
					 $pageData["state"] = $this->db->get("state");
					 $pageData["location_type"]=$this->db->get("location_type");

					 if($isUpdate) {
							 $pageData["form_button"] = "Update";
							 $pageData["form_action"] = "account/handleUpdate";
							 $pageData["isUpdate"] = true;
						 } else {
							 $pageData["form_button"] = "Create";
							 $pageData["form_action"] = "account/handleCreate";
						 }
					 $this->phpsession->flashsave('error',Errors::getError(2));
					 $pageData["default_values"] = array_merge($_POST);
					 $headerData = array(
						 "pageTitle"=>"Login | My Account | Washington Homebrewers Association",
						 "pageStyleIndex"=>0, /* Header/Background/Logo pairing */
						 "styleIncludes"=>array("<link rel=\"stylesheet\" type=\"text/css\" href=\"/styles/form.css\" />"),
						 "selectedNav"=>"" /* Selected top level nav */
						 );
					 $footerData = array();
						 //redirect("account/update");
					 $this->load->view("PageTemplate_header.php",$headerData);
					 $this->load->view("account/create.php",$pageData);
					 $this->load->view("PageTemplate_footer.php",$pageData);
				 } else {
					 $this->load->model('AccountModel'); // Account model
					 $now = date("Y-m-d H:i:s");
					 $profileDataArray = array(
						 "aha_number"=>$_POST["aha_number"],
						 "fname"=>$_POST["fname"],
						 "lname"=>$_POST["lname"],
						 "username"=>$_POST["username"]);
					 $contactDataArray = array(
						 "phone"=>$_POST["phone"],
						 "cell"=>$_POST["cell"],
						 "fax"=>$_POST["fax"],
						 "email"=>$_POST["email"],
						 "best_time"=>$_POST["best_time"],
						 "best_days"=>$_POST["best_days"]);
					 $userDataArray = array(
						 "passwd"=>$_POST["passwd"],
						 "username"=>$_POST["username"]
						 );
					 $locDataArray = array(
						 "name"=>$_POST["name"],
						 "address1"=>$_POST["address1"],
						 "address2"=>$_POST["address2"],
						 "city"=>$_POST["city"],
						 "state"=>$_POST["state"],
						 "zipcode"=>$_POST["zipcode"],
						 "location_type"=>$_POST["location_type"],
						 "xLat"=>"",
						 "yLat"=>""
						 );
					 if($isUpdate){
							 $this->AccountModel->updateAccount($profileDataArray,$contactDataArray,$userDataArray,$locDataArray,$now);
							 $this->setLogin($_POST["username"],$_POST["fname"]);
							 redirect("account/update");
						 } else {
							 $this->AccountModel->createAccount($profileDataArray,$contactDataArray,$userDataArray,$locDataArray,$now);
							 $this->setLogin($_POST["username"],$_POST["fname"]);
							 redirect("welcome");
						 }// end isUpdate
				 } // end isValidated
		 }
	 public function handleUpdate() {
			 $this->handleCreate(true); // run Create with "isUpdate";
		 }
}
?>